package org.scboy.dbms.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.BaseAppServerDao;
import org.scboy.dbms.dao.BaseServersDao;
import org.scboy.dbms.service.BaseServersService;
import org.scboy.dbms.sftp.SshClient;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

@Service
public class BaseServersServiceImp implements BaseServersService {

	Log log=LogFactory.get();
	
	@Autowired
	EntityFactory factory;
	
	@Override
	public Page page(Model params) {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		BaseAppServerDao appServerDao=factory.getDao(BaseAppServerDao.class);
		params.orderBy("ip");
		Page page = dao.page(params);
		for (Object data : page.getData()) {
			Model model=(Model)data;
			model.add("notStart", 0);
			model.add("starting", 0);
			model.add("runing", 0);
			
			//0未启动，1在启动，2已启动，3启动异常
			List<Model> groupDatas= appServerDao.groupByStatus(Model.create().add("ip", model.getString("ip")));
			for (Model gData : groupDatas) {
				switch (gData.getInt("status")) {
				case 0: {
					model.add("notStart",gData.getInt("countNum"));
					break;
				}
				case 1: {
					model.add("starting",gData.getInt("countNum"));
					break;
				}
				case 2: {
					model.add("runing",gData.getInt("countNum"));
					break;
				}
				default:
					break;
				}
			}
		}
		return page;
	}

	@Override
	public boolean add(Model params) {
		
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		
		String ip=params.getString("ip");
		
		//ip不存在
		if(StrUtil.isEmpty(ip)) {
			return false;
		}
		
		//判断IP是否已在数据库
		long count=dao.count(Model.create().add("ip", ip));
		if(count>0) {
			return false;
		}
		
		int result=dao.insert(params);
		if(result>0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public boolean delete(String ip) {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		BaseAppServerDao serverDao=factory.getDao(BaseAppServerDao.class);
		
		//检查是否有正在启动的服务，获取已经启动的服务
		long count=serverDao.count(Model.create().add("ip", ip).IN("status", new String[] {"1","2"}));
		if(count>0) {
			return false;
		}
		
		//删除微服务部署记录
		serverDao.delete(Model.create().add("ip", ip));
		
		//删除服务器
		int result=dao.delete(Model.create().add("ip", ip));
		if(result>0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public boolean update(Model params) {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		int result=dao.update(params);
		if(result>0) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Model get(String ip) {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		return dao.get(Model.create().add("ip", ip));
	}

	@Override
	public List<Model> list() {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		return dao.select(Model.create().orderBy("ip").add("serverState", 1));
	}

	@Override
	public List<Model> listAll() {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		return dao.select(Model.create().orderBy("ip"));
	}

	@Override
	public Model health(String ip) {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		Model server=dao.get(Model.create().add("ip", ip));
		Model health=Model.create();
		health.add("memory", Model.create().add("total", 0).add("used", 0).add("free", 0).add("buffCache", 0));
		health.add("cpu", 0);
		health.add("disk", new ArrayList<Model>());
		if(server.getInt("serverState")==1) {
			try {
				SshClient ssh=new SshClient(ip, server.getInt("port"), server.getString("adminAccount"), server.getString("adminPassword"));
				health.add("memory", ssh.getMem());
				health.add("cpu", ssh.getCpu());
				health.add("disk", ssh.getDisk());
				ssh.close();
			} catch (Exception e) {
				//log.warn("无法读取"+ip+"系统信息。",e);
			}
		}
		return health;
	}

	@Override
	@Async
	public void restart(String ip) {
		BaseServersDao dao=factory.getDao(BaseServersDao.class);
		Model server=dao.get(Model.create().add("ip", ip));
		SshClient client=new SshClient(ip, server.getInt("port"), server.getString("adminAccount"), server.getString("adminPassword"));
		client.exeCommand("shutdown -r now");
		client.close();
	}
}
